#!/bin/bash

#采集cpu信息

get_time=$( date +%Y%m%d%H%M%S )

cpu_info(){
	top -bn 1|awk '/^%Cpu/ {print $2,$4,$8}'|while read us sy idle
	do
		used_cpu=$( echo "100 - $idle" | bc )
		echo "$get_time    user_process:$us  system_process:$sy  idle:$idle  used:$used_cpu" | tee -a /var/log/performance_usage.log
	done
	return 0
}

mem_info(){
	free -m |awk '/^Mem/{print $2,$3,$4,$5,$6,$7}'|while read total used free shared buff_cache available
	do
		echo "$get_time    total_mem:$total  used_mem:$used  free_mem:$free  shared_mem:$shared  buff_cache_mem:$buff_cache  available_mem:$available" | tee -a /var/log/performance_usage.log
	done 
	
}

disk_info(){
	disk_total=$( lsblk | grep "^sd" | awk '{print $1,$2}' )
	df -Th | egrep "/$|home$|boot$" | awk '{print $3,$4,$5,$6,$7}' | while read size used free used_percent name
	do
		echo "$get_time   disk_size:$size   used_disk:$used   free_disk:$free   used_percent_disk:$used_percent  name_disk:$name   total:$disk_total" | tee -a /var/log/performance_usage.log
	done
	

}

process_info(){
	#总计进程
	top -bn 1 | awk '/^Tasks/ {print $2,$4,$6,$8,$10}' | while read p_total running sleeping stopped zombie
	do
		echo "$get_time   pro_total:$p_total   pro_running:$running   pro_sleeping:$sleeping   pro_stopped:$stopping   pro_zombie:$zombie" | tee -a /var/log/performance_usage.log
		
	done
	ps aux |tail -n +2| sort -n -k3 -r | head -5 | awk '{print $1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11}' |while read USER PID CPU MEM VSZ RSS TTY STAT START TIME COMMAND
	do
		echo "$get_time   pro_user:$USER   pid:$PID   pro_cpu:$CPU   pro_mem:$MEN   pro_vsz:$VSZ   pro_rss:$RSS   pro_tty:$TTY   pro_stat:$STAT   pro_start:$START   pro_time:$TIME   pro_command:$COMMAND"| tee -a /var/log/performance_usage.log
	done

	ps aux |tail -n +2| sort -n -k4 -r | head -5 | awk '{print $1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11}' |while read USER PID CPU MEM VSZ RSS TTY STAT START TIME COMMAND
        do
                echo "$get_time   pro_user:$USER   pid:$PID   pro_cpu:$CPU   pro_mem:$MEN   pro_vsz:$VSZ   pro_rss:$RSS   pro_tty:$TTY   pro_stat:$STAT   pro_start:$START   pro_time:$TIME   pro_command:$COMMAND"| tee -a /var/log/performance_usage.log
        done

	
}

cpu_info
mem_info
disk_info
process_info
